layui.use(['table', 'admin', 'ax','laydate'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
    var laydate = layui.laydate;

    // 初始化日期选择器 - Initialize date picker
    laydate.render({
    	elem:'#startTime'
    });
    
    // 初始化日期选择器 - Initialize date picker
    laydate.render({
    	elem:'#endTime'
    });
    
    /**
     * 出库订单 - Outbound Order
     */
    var OutOrder = {
        tableId: "outOrderTable"
    };
    
    /**
     * 初始化出库订单表格列 - Initialize outbound order table columns
     */
    OutOrder.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'ID'},
            {field: 'customerNumber', title: 'Customer Order No.', style:'color: #2b85e4;font-weight: 600;',width:150,event: 'detailedSign'},
            {field: 'outOrderStatus', sort: true, title: 'Order Status'},
            {field: 'setMentiontime', sort: true, title: 'Shipment Date'},
            {field: 'createUserName', title: 'Created By'},
            {field: 'getUnitId', title: 'Delivery Unit ID'},
            {field: 'kilometer', title: 'Distance (km)'},
            {field: 'getUnit', title: 'Delivery Unit', style:'font-weight: 600;',width:180},
            {field: 'getLocation', title: 'Delivery Location',width:250},
            {field: 'outWay', title: 'Outbound Method'},
            {field: 'note', title: 'Remarks',width:120, totalRowText: 'Total:'},
            {field: 'sumVolume', title: 'Volume', totalRow: true},
            {field: 'sumNum', title: 'Quantity', totalRow: true},
            {field: 'sumMoney', title: 'Value', totalRow: true},
            {field: 'storehouseName', title: 'Warehouse Name'},
            {field: 'outCustomerName', title: 'Customer Name'},
            {field: 'outOrderNumber', sort: true, title: 'Outbound Order No.', style:'font-weight: 600;',event: 'detailedSign'},
            {field: 'createTime', sort: true, title: 'Creation Time'},
            {field: 'submitTime', sort: true, title: 'Submission Time'},
            {field: 'submitterName', title: 'Submitted By'},
            {fixed: 'right',width: 80,align: 'center', toolbar: '#tableBar', title: 'Operations'}
        ]];
    };
        
        /**
         * 点击查询按钮 - Click search button
         */
        OutOrder.search = function () {
            var queryData = {};
            queryData['condition'] = $("#condition").val();
        	queryData['outCustomerId'] = $("#outCustomerId").val();
            queryData['outStorehouseId'] = $("#outStorehouseId").val();
            queryData['outOrderStatus'] = $("#outOrderStatus").val();
	        queryData['startTime'] = $("#startTime").val();
	        queryData['endTime'] = $("#endTime").val();
            table.reload(OutOrder.tableId, {
                where: queryData, page: {curr: 1},
                 done:function () {
                }
            });
        };
        
        // 渲染出库订单表格 - Render outbound order table
        var tableResult = table.render({
            elem: '#' + OutOrder.tableId,
            url: Feng.ctxPath + '/outOrder/getConfirmlist',
            page: true,
            limit: 60,
			limits:[40,60,120,240,360,480,1200],
        	height: "full-60",
            cellMinWidth: 100,
            totalRow: true ,//开启合计行 - Enable total row
        	toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板 - Enable header toolbar and bind left template
            cols: OutOrder.initColumn()
        });

    // 批量确认 - Batch confirm
    OutOrder.confirm = function () {
        var checkStatus = table.checkStatus('outOrderTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            layer.confirm('Confirm selected orders?', function(index){
            	layer.close(index);
            	var msg;
                $.ajax({
                	url:Feng.ctxPath + "/outOrder/confirm?ids="+ids,
                	cache: false,
                	dataType:"json",
                	beforeSend:function(){
                    	//弹出加载中 - Show loading
                		msg = layer.msg('Submitting... Please wait', {
	              			  icon: 16,
	              			  shade: [0.2,'#000'], //0.2 opacity black background
	              			  time: false
                		});
                	},
                	success:function(data){
					console.log(data)
                    	layer.close(msg); 
                		if (data.success) {
                        	Feng.success("Confirmation successful!");
                			table.reload(OutOrder.tableId);
						} else {
							if (data.message !=null &&data.message!='') {
			    				var msg2 =  layer.open({
				  					  title: 'Notification' ,
				  					  content: data.message,
				  					  btn: ['Confirm'],
				  					  yes: function (){
				  						  	layer.close(msg2);
                							table.reload(OutOrder.tableId);
				  					  }
			    				});      
							} else {
	  		                    Feng.error("Confirmation failed!");
                				table.reload(OutOrder.tableId);
							}
					}
                	},
                	error:function(data){
                    	layer.close(msg); 
                        Feng.error("Confirmation failed! " + data.responseJSON.message)
            			table.reload(OutOrder.tableId);
                	}
                })
            }); 
        } else {
            layer.alert('Please select at least one record');
        }
    };

        // 搜索按钮点击事件 - Search button click event
        $('#btnSearchout').click(function () {
        	OutOrder.search();
        });

	    // 批量确认按钮点击事件 - Batch confirm button click event
	    $('#btnConfirm').click(function () {
	        OutOrder.confirm();
	    });

	    // 单击行事件 - Single row click event
	    table.on('row(' + OutOrder.tableId + ')', function (obj) {
	        var data = obj.data;
			$('div[lay-id="' + OutOrder.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样 - Restore other rows to original state
			$('div[lay-id="' + OutOrder.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色 - Change current row color
	    });

        // 工具条点击事件 - Toolbar click event
        table.on('tool(' + OutOrder.tableId + ')', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'confirm') {
				submit = 0
	            layer.open({
            type: 2,
            title: 'Outbound Order Confirmation',
            area: ['1000px', '800px'],
            content: Feng.ctxPath + '/outOrder/toConfirm1?id=' + data.id,
	                end: function () {
	            		if(submit == 1){
                			table.reload(OutOrder.tableId);
						}
	                }
	            });
        	} else if (layEvent === 'detailedSign') {
                layer.open({
                    type: 2,
                    title: 'Order Details',
                    area: ['1000px', '500px'],
                    anim: 5,
                    content: Feng.ctxPath + '/outOrderDetailed/toQuery?detailedOutNumber=' + data.outOrderNumber,
                });
            }
        });


});
